package leetcode.L500;

import java.util.Stack;

public class EX224 {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        int res = 0,sign = 1;
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char temp = s.charAt(i);
            if(isDigit(temp)){
                int num = temp-'0';
                while (i+1<len&&isDigit(s.charAt(i+1))){
                    num = num*10+s.charAt(++i)-'0';
                }
                res = num*sign +res;
            }
            else if(temp=='+'){
                sign = 1;
            }
            else if(temp=='-'){
                sign = -1;
            }
            else if(temp=='('){
                stack.push(res);
                stack.push(sign);
                sign = 1;
                res = 0;
            }
            else if(temp==')'){
                res = stack.pop()*res+stack.pop();
            }
        }
        return res;
    }
    public boolean isDigit(char a){
        if(a=='+'||a=='-'||a=='('||a==')'||a==' '){
            return false;
        }else {
            return true;
        }
    }
}
